function getSolution(solutionId) {
	for(var i=0; i< jsonData.length; i++) {
		var data = jsonData[i];
		if(solutionId == data.solutionId){
			return data;
		}
	}
}

function getSolutionMutex(solutionId) {
	var solution = getSolution(solutionId);
	return solution.solutionMutex;
}

function setDefalutTab(solutionId, checked) {
	var solution = getSolution(solutionId);
	var stepList = solution.stepList;
	for(var j=0; j< stepList.length; j++){
		var mixList = stepList[j].mixList;
		for(var k=0; k< mixList.length; k++){
			var mixLists = mixList[k].mixList;
			for(var l=0; l< mixLists.length; l++){
				var mixItem = mixLists[l];
				var mixNeeded = mixItem.mixNeeded;
				var checkItem = $("#mix-" + mixItem.mixId);
				if(checked) {
					if(l == 0){
						checkItem.attr("checked",true); 
					} else {
						checkItem.attr("checked",false);
					}
					checkItem.attr("disabled",false);
				} else {
					checkItem.attr("checked",false);
					checkItem.attr("disabled",true);
				}
				checkItem.checkboxradio("refresh");
			}
		}
	}
	var foodList = solution.foodList;
	for(var i=0; i< foodList.length; i++){
		var foodId = foodList[i].productId;
		var solutionId = foodList[i].solutionId;
		var foodNeeded = 0;
		var item = $("#product-" + solutionId + "-" + foodId);
		if(checked) {
			if(foodNeeded == 1) {
				item.attr("disabled",true);
			} else {
				item.attr("disabled",false);
			}
		} else {
			item.attr("checked", false);
			item.attr("disabled",true);
		}
		item.checkboxradio("refresh");
	}
	
	var careList = solution.careList;
	for(var i=0; i< careList.length; i++){
		var careId = careList[i].careId;
		var careNeeded = careList[i].careNeeded;
		var item = $("#care-" + careId);
		if(checked) {
			 item.attr("checked",true);
			if(careNeeded == 1) {
				item.attr("disabled",true);
			} else {
				item.attr("disabled",false);
			}
		} else {
			item.attr("checked", false);
			item.attr("disabled",true);
		}
		item.checkboxradio("refresh");
	}
	renderTitle();
}

function getPriorityByProductId(id) {
	var solutionId = id.substring(0, id.indexOf("-"));
	var solution = getSolution(solutionId);
	return solution.priority;
}

function getSolutionNameByProductId(id) {
	var solutionId = id.substring(0, id.indexOf("-"));
	var solution = getSolution(solutionId);
	return solution.solutionName;
}

function returnResult(panel) {
	$('#resultPanel').css('display','block');
	$('#' + panel).css('display','none');
	if(scrollToId != "") {
		document.getElementById(scrollToId).scrollIntoView();
	}
}

function getProductList(productList, checkedIds, uncheckedIds, mixList) {
	var item = $("#mix-" + mixList.mixId);
	var checked = item.prop("checked");
	var products = mixList.detailList;
	for(var i=0; i< products.length; i++) {
		var product = products[i];
		if(checkedIds.indexOf(product.productId) > -1) {
			break;
		}else if(uncheckedIds.indexOf(product.productId) > -1) {
			if(checked){
				checkedIds.push(product.productId);
				uncheckedIds.removevalue(product.productId);
			}
		} else {
			productList.push(product);
			if(checked){
				checkedIds.push(product.productId);
			} else {
				uncheckedIds.push(product.productId);
			}
		}
	}
}

function renderTitle() {
	var productList = [];
	var foodList = [];
	var checkedIds = [];
	var uncheckedIds = [];
	var ifEmptyProduct = true;
	var ifEmptyFood = true;
	var ifEmptyCare = true;
	var productTableHtml = "<table>";
	var foodTableHtml = "<table>";
	var careTableHtml = "<table>";
	var nums = 0;
	var nums1 = 0;
	for(var i=0; i< jsonData.length; i++) {
		var solution = jsonData[i];
		var stepList = solution.stepList;
		for(var j=0; j< stepList.length; j++){
			var mixList = stepList[j].mixList;
			for(var k=0; k< mixList.length; k++){
				var mixLists = mixList[k].mixList;
				for(var l=0; l< mixLists.length; l++){
					getProductList(productList, checkedIds, uncheckedIds, mixLists[l]);
				}
			}
		}
		
		var foodList = solution.foodList;
		for(var j=0; j< foodList.length; j++){
			var item = $("#product-" + foodList[j].solutionId + "-" + foodList[j].productId);
			if(item.prop("checked")){
				ifEmptyFood = false;
				var labelHtml = '<font id="label-food-' + foodList[j].productId +'">' + '【' + foodList[j].productName +'】'+'</font>';
				if(nums1%3 == 0) {
					if(nums1 == 0) {
						foodTableHtml += "<tr>";
					} else {
						foodTableHtml += "</tr><tr>";
					}
				}
				foodTableHtml += "<td>" + labelHtml + "</td>";
				nums1++;
			}
		}
		
		var careList = solution.careList;
		for(var j=0; j< careList.length; j++){
			var item = $("#care-" + careList[j].careId);
			if(item.prop("checked")){
				ifEmptyCare = false;
				var labelHtml = '<font id="label-care-' + careList[j].careId +'">' + '【' + careList[j].careName +'】'+'</font>';
				if(nums%3 == 0) {
					if(nums == 0) {
						careTableHtml += "<tr>";
					} else {
						careTableHtml += "</tr><tr>";
					}
				}
				careTableHtml += "<td>" + labelHtml + "</td>";
				nums++;
			}
		}
	}
	if(nums1%3 != 0) {
		while(nums1%3 != 0) {
			foodTableHtml += "<td>&nbsp;</td>"
			nums1++;
		}
	}
	foodTableHtml += "</tr></table>";
	if(nums%3 != 0) {
		while(nums%3 != 0) {
			careTableHtml += "<td>&nbsp;</td>"
			nums++;
		}
	}
	careTableHtml += "</tr></table>";
	nums = 0;
	for(var i=0; i< productList.length; i++) {
		var product = productList[i];
		if(checkedIds.indexOf(product.productId) > -1) {
			ifEmptyProduct = false;
			var labelHtml = '<font id="label-product-' + product.productId +'">' + '【' + product.productName +'】'+'</font>';
			if(nums%3 == 0) {
				if(nums == 0) {
					productTableHtml += "<tr>";
				} else {
					productTableHtml += "</tr><tr>";
				}
			}
			productTableHtml += "<td>" + labelHtml + "</td>";
			nums++;
		}
	}
	if(nums%3 != 0) {
		while(nums%3 != 0) {
			productTableHtml += "<td>&nbsp;</td>"
			nums++;
		}
	}
	productTableHtml += "</tr></table>";
	$("#productList").html("");
	if(ifEmptyProduct) {
		$("#productList").append("无");
	} else {
		$("#productList").append(productTableHtml);
	}
	$("#foodList").html("");
	if(ifEmptyFood) {
		$("#foodList").append("无");
	} else {
		$("#foodList").append(foodTableHtml);
	}
	$("#careList").html("");
	if(ifEmptyCare) {
		$("#careList").append("无");
	} else {
		$("#careList").append(careTableHtml);
	}
}

function getRenderData(jsonData) {
	var renderData = cloneJson(jsonData);
	for(var i=0; i< jsonData.length; i++) {
		var solution = jsonData[i];
		var stepList = solution.stepList;
		for(var j=0; j< stepList.length; j++){
			var mixList = stepList[j].mixList;
			renderData[i].stepList[j].mixList = [];
			var daylength = mixList[0].mixList.length;
			var nightlength = mixList[1].mixList.length;
			if(daylength < nightlength) {
				daylength = nightlength;
			}
			for(var k=0; k< daylength; k++){
				var arr = {mixList:[]};
				if(mixList[0].mixList[k]) {
					arr.mixList.push(mixList[0].mixList[k]);
				} else {
					arr.mixList.push({mixId:-1});
				}
				if(mixList[1].mixList[k]) {
					arr.mixList.push(mixList[1].mixList[k]);
				} else {
					arr.mixList.push({mixId:-1});
				}
				renderData[i].stepList[j].mixList.push(arr);
			}
		}
	}
	return renderData;
}

function initNavbars(){
	var navbarsWidth = $("#navbars").width();
	var ulWidth = jsonData.length*200;
	var scrollWidth = ulWidth-navbarsWidth;
	$( "#navbars ul" ).css("min-width", ulWidth + "px");
	if($( "#navbars").width() < $( "#navbars ul" ).width()){
		$("#navbars .icon-right").css("display", 'block');
		$("#navbars").scroll(function () {
			 var scroll = $( "#navbars").scrollLeft();
			 if(scroll > 0) {
				 $( "#navbars .icon-left").css("display", 'block'); 
				 $( "#navbars .icon-right").css("display", 'block'); 
			 }
			 if(scroll == 0) {
				 $( "#navbars .icon-left").css("display", 'none'); 
			 } 
			 var cha =  scrollWidth - scroll;
			 if( cha < 10) {
				 $( "#navbars .icon-right").css("display", 'none'); 
			 }
		});
		 $("#navbars .icon-right").bind("tap", function(event) {
			 var scroll = $( "#navbars").scrollLeft()+100;
			 $( "#navbars").scrollLeft(scroll);
			 event.stopPropagation();
			 event.preventDefault();
		 }); 
		 $("#navbars .icon-left").bind("tap", function(event) {
			 var scroll = $( "#navbars").scrollLeft()-100;
			 $( "#navbars").scrollLeft(scroll);
			 event.stopPropagation();
			 event.preventDefault();
		 }); 
	}
}

function resultInit(ctx){
	if(jsonData.length == 0){
		$("#tabs").html("没有符合条件的方案!");
		return;
	}
	$( "#navbars ul" ).html(
		$( "#navTemplate" ).render(jsonData)
	).navbar();
	
	initNavbars();
	 
	var renderData = getRenderData(jsonData);
	renderData.noimgUrl = onimg;
	$( "#navbars" ).after(
		$( "#contentTemplate" ).render(renderData)
	);
	$( "#tabs" ).tabs( "refresh" );
	$( "#navbars ul li:first-child a" ).click();
	$( "#tabs" ).trigger('create');
	for(var i=0; i< jsonData.length; i++) {
		var data = jsonData[i];
		var firstSolutionId = data.solutionId;
		var bool = false;
		if(i == 0) {
			bool = true;
		}
		$("#" + firstSolutionId).attr("checked", bool).checkboxradio("refresh");
		setDefalutTab(firstSolutionId, bool);
	}
	$( "#tabs" ).trigger('create');
	
	renderTitle();
	$("#navbars li input").click(function() {
		 if($(this).attr("checked")) {
			var inputs = $("#navbars li input");
			for(var i=0;i< inputs.length; i++) {
				var item = inputs[i];
				var solutionMutex = getSolutionMutex(this.id);
				if(item.checked && solutionMutex.indexOf(item.id) > -1) {
					$(this).attr("checked", false).checkboxradio("refresh");
					showTip("存在互斥方案：" + item.value);
					return;
				}
			}
			setDefalutTab(this.id, true);
         } else {
         	setDefalutTab(this.id, false);
         } 
		 $('#navbars ul li a').removeClass('ui-btn-active');
		 $(this).parent().parent().addClass('ui-btn-active');
		 document.getElementById("navbars").scrollIntoView();
	});
	
	$(".product input").click(function() {
		if($(this).attr("checked")) {
			mixMutex($(this).attr("name"));
		}
		renderTitle();
	});
	$(".food input, .care input").click(function() {
		renderTitle();
	});
	
	$(".product .item, .food .bottom, .care button").click(function() {
		$('#resultPanel').css('display','none');
		$('#detailPanel').css('display','block');
		var url = ctx + "/expert/"+ $(this).attr("type") +"/desc?id=" + $(this).attr("value");
		window.open(url,"datailFrame");
		document.getElementById("detailPanel").scrollIntoView();
		scrollToId = $(this).attr("type") + "-" + $(this).attr("value");
	});
	$(".product .title font, h3 a").click(function() {
		var id = $(this).attr("value");   
		var o = document.getElementById(id);
		o.click();
	});
}

function getMixParent(mixId){
	for(var i=0; i< jsonData.length; i++) {
		var solution = jsonData[i];
		var stepList = solution.stepList;
		for(var j=0; j< stepList.length; j++){
			var mixList = stepList[j].mixList;
			for(var k=0; k< mixList.length; k++){
				var mixLists = mixList[k].mixList;
				for(var l=0; l< mixLists.length; l++){
					var mixItem = mixLists[l];
					if(mixItem.mixId == mixId) {
						return mixLists;
					}
				}
			}
		}
	}
}

function mixMutex(mixId) {
	var mixList = getMixParent(mixId);
	for(var i=0; i< mixList.length; i++) {
		var mixItem = mixList[i];
		if(mixItem.mixId!= mixId) {
			var item = $("#mix-" + mixItem.mixId);
		    item.attr("checked", false).checkboxradio("refresh");
		}
	}
}

function getResultProductData(mixIdList, checkedProducts, solution){
	var productIds = [];
	var stepList = solution.stepList;
	for(var j=0; j< stepList.length; j++){
		var mixList = stepList[j].mixList;
		for(var k=0; k< mixList.length; k++){
			var mixLists = mixList[k].mixList;
			for(var l=0; l< mixLists.length; l++){
				var mixItem = mixLists[l];
				var checkItem = $("#mix-" + mixItem.mixId);
				if(checkItem.prop("checked") == true){
					mixIdList.push(mixItem.mixId);
					var products = mixItem.detailList;
					for(var m=0; m< products.length; m++){
						var product = products[m];
						if(productIds.indexOf(product.productId) == -1) {
							productIds.push(product.productId);
							checkedProducts.push(product);
						}
					}
				}
			}
		}
	}
}

function getResultJsonData() {
	var json = {
			'totalProductMoney' : 0,
			'totalFoodMoney' : 0,
			'totalCareMoney' : 0,
			'solutionList' : []
		}
	var inputs = $("#navbars li input");
	var totalProductMoney = 0;
	var totalFoodMoney = 0;
	var totalCareMoney = 0;
	for(var i=0; i< inputs.length; i++) {
		var item = inputs[i];
		var solution = getSolution(item.id);
		var solutionObj = {
				'productList':[],
				'foodList':[],
				'careList':[],
				'mixList': [],
				'totalMoney' : 0,
				'solutionName':solution.solutionName,
				'solutionId':solution.solutionId	
			};
		if(!item.checked) {
			solutionObj.checked = false;
			json.solutionList.push(solutionObj);
			continue;
		}
		solutionObj.checked = true;
		var money = 0;
		var length = 0;
		var mixList = [];
		var productList = [];
		getResultProductData(mixList, productList, solution);
		for(var j=0; j< productList.length; j++){
			var productObj = $.extend({}, productList[j]);
			length++;
			money += productList[j].productPrice*productList[j].productAmount;
			solutionObj.productList.push(productObj);
		}
		solutionObj.mixList = mixList;
		solutionObj.productLength = length;
		solutionObj.totalMoney += money;
		totalProductMoney += money;
		money = 0;
		length = 0;
		var foodList = solution.foodList;
		for(var j=0; j< foodList.length; j++){
			var foodId = foodList[j].productId;
			var fItem = $("#product-" + foodList[j].solutionId + "-"  + foodId);
			if(fItem.prop("checked") == true){
				var foodObj = $.extend({}, foodList[j]);
				length++;
				money += foodList[j].productPrice*foodList[j].productAmount;
				solutionObj.foodList.push(foodObj);
			}
		}
		solutionObj.foodLength = length;
		solutionObj.totalMoney += money;
		totalFoodMoney += money;
		money = 0;
		length = 0;
		var careList = solution.careList;
		for(var j=0; j< careList.length; j++){
			var careId = careList[j].careId;
			var cItem = $("#care-" + careId);
			if(cItem.prop("checked") == true){
				var careObj = $.extend({}, careList[j]);
				length++;
				money += careList[j].carePrice;
				solutionObj.careList.push(careObj);
			}
		}
		solutionObj.careLength = length;
		solutionObj.totalMoney += money;
		totalCareMoney += money;
		json.solutionList.push(solutionObj);
	}
	json.totalProductMoney = totalProductMoney;
	json.totalFoodMoney = totalFoodMoney;
	json.totalCareMoney = totalCareMoney;
	return json;
}

function makeSure() {
	$('#resultPanel').css('display','none');
	$('#surePanel').css('display','block');
	var json = getResultJsonData();
	$( "#sureDetail div" ).html(
		$( "#sureTemplate" ).render(json)
	).trigger('create');
	scrollToId = "resultPanel";
}

function setSubmitData(){
//	loading('正在提交，请稍等...');
//	jQuery.ajax({  
//        type : 'POST',  
//        url : ctx + "/expert/customerSolution/save",  
//        dataType : 'json', 
//        data : {'jsonData':JSON.stringify(jsonData)},
//        success : function(data) {  
//        	showTip("开单成功");
//        	$( "#sureDetail" ).html("");
//        	$( "#sureDetail" ).append(
//    			"<div class='result'>产品、护理已经放入购物车！<br><br>" +
//        		"<a href='" + ctx + "/cash/member/detail?id=" +customerId +"'>点击结算</a><div>"
//        	);
//        },  
//        error : function(data) { 
//        	showTip("开单失败");
//        }  
//  }); 
}
